package com.xunge.filter;

import com.xunge.utils.CurrentHolder;
import com.xunge.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String URI = request.getRequestURI(); // 获取请求的URI
        if(URI.equals("/login")){
            log.info("登录请求，放行");
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("token"); // 获取请求头中的token
        if(token == null || token.isEmpty()){
            log.info("token不存在，拦截请求,响应401状态码");
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            log.info("token: {}", claims);
            log.info("当前用户id为：{}",empId);
            CurrentHolder.setCurrentId(empId);
        } catch (Exception e) {
            log.info("token错误，拦截请求,响应401状态码");
            response.setStatus(401);
            return;
        }
        // 放行
        log.info("token验证成功，放行");
        filterChain.doFilter(request,response);

        // 释放资源
        CurrentHolder.remove();
    }
}
